<?php
namespace Tbf\Component\Excel\Exporter;
use Tbf\Component\Io\StringWriterInterface;
use Tbf\Component\Arrays\ArrayReaderInterface;

/**
 * CsvExporter read data from $src save output to $dest
 */
class CsvExporter implements ArrayExporterInterface
{
    /** @var  \Tbf\Component\Arrays\ArrayReaderInterface */
    protected $src;
    /** @var  StringWriterInterface */
    protected $dest;
    /** @var  boolean */
    protected $is_first_line;

    /**
     * @param \Tbf\Component\Arrays\ArrayReaderInterface $src
     * @param StringWriterInterface $dest
     * @return null
     */
    public function export(ArrayReaderInterface $src,StringWriterInterface $dest)
    {
        $this->src = $src;
        $this->dest = $dest;
        $this->is_first_line = true;
        while (true) {
            $row = $this->src->readRow();
            if ($row === null) {
                return;
            }
            $this->exportRow($row);
        }
        return null;
    }
    protected function exportRow(array $row)
    {
        $output = '';
        //最后的换行问题
        if (!$this->is_first_line) {
            $output .= "\n";
        }
        $this->is_first_line = false;
        //最后的,号问题
        $is_first = true;
        foreach ($row as $key=>$value) {
            if (!$is_first) {
                $output .= ',';
            }
            $is_first = false;
            //这里使用=解决数值精度问题
            if (is_numeric($value)){
                $output .= '="'.str_replace('"', '""' ,$value).'"';
            }else{
                $output .= '"'.str_replace('"', '""' ,$value).'"';
            }
        }
        $this->dest->write($output);
    }
}
